package com.spider.gp.processor;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.spider.gp.constant.UrlConstant;
import com.spider.gp.dao.HotMoneyInfo;
import com.spider.gp.dao.HotMoneyInfoDao;
import com.spider.gp.dao.LongHuBang;
import com.spider.gp.dao.LongHuBangDao;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.processor.PageProcessor;
import us.codecraft.webmagic.selector.Selectable;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * description:
 *
 * @author clare
 * @date 2022/05/20 08:56
 **/
@Component
public class LonghubangProcessor implements PageProcessor {
    private Site site = Site.me().setRetryTimes(3).setSleepTime(1000);

    @Autowired
    private HotMoneyInfoDao hotMoneyInfoDao;
    @Autowired
    private LongHuBangDao longHuBangDao;

    @Override
    public void process(Page page) {
        if (page.getUrl().toString().equals(UrlConstant.THS_LONG_HU_BANG)) {
            List<String> urlList = new ArrayList<String>();


            List<Selectable> nodes =  page.getHtml().xpath("//div[@class=\"stockcont\"]").nodes();
            List<Selectable> nodesTop =  page.getHtml().xpath("//div[@class=\"twrap\"]//table//tbody//tr").nodes();
            String reportTime =  page.getHtml().xpath("//div[@class=\"sel-date-panel\"]").$("input","value").get();
            LambdaQueryWrapper<LongHuBang> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(LongHuBang::getReportTime, reportTime);
            longHuBangDao.delete(wrapper);
//            if (total != null && total > 0){
//                return;
//            }
            if (nodes != null && nodes.size() > 0) {
                for (int i = 0 ; i< nodes.size() ; i ++) {//Selectable node : nodes 取 第一个跟最后一个
                    String mx = nodes.get(i).xpath("//p/text()").get();//上榜原因
                    String code  = mx.substring((mx.indexOf("(") + 1), (mx.indexOf(")"))); //编码

                    if (code.startsWith("688") || code.startsWith("900")){
                        //科创板不看
                        continue;
                    }
                    //明细
                    String name  = mx.substring(0, (mx.indexOf("("))); //名称

                    if (name.contains("退")){
                        //退市不看
                        continue;
                    }

                    String cjmx = nodes.get(i).xpath("//div[@class=\"cell-cont cjmx\"]//p/tidyText()").get();//成交明细
                    urlList = page.getHtml().xpath("//div[@class=\"cell-cont cjmx\"]//p").$("a", "href").all();
                    List<Selectable> nodesBuy5 =  nodes.get(i).xpath("//table[@class=\"m-table m-table-nosort mt10\"][1]//tbody//tr").nodes();//
                    List<Selectable> nodesSell5 =  nodes.get(i).xpath("//table[@class=\"m-table m-table-nosort mt10\"][2]//tbody//tr").nodes();//
                    StringBuffer TotalBuy = new StringBuffer();
                    StringBuffer TotalSell = new StringBuffer();

                    StringBuffer YZBuyMX = new StringBuffer();//游资买5明细
                    StringBuffer YZBuy = new StringBuffer(); //买的游资
                    StringBuffer YZSellMX = new StringBuffer(); //游资卖5明细
                    StringBuffer YZSell = new StringBuffer(); //卖的游资

                    nodesTop.forEach(e -> {
                        //涨跌幅
                        String codeTop = e.xpath("//td[2]/tidyText()").get(); //编码

                        if (!codeTop.equals(code)){
                            return;
                        }

                        String labelType =  e.xpath("//td[1]/tidyText()").get(); // 是否是 3日 的
                        if (!labelType.equals("3日") && mx.contains("个交易日")){
                            return;
                        }
                        if (Strings.isBlank(labelType.trim()) && mx.contains("个交易日")){
                            return;
                        }


                        String price = e.xpath("//td[4]/tidyText()").get(); //现价
                        String zdf = e.xpath("//td[5]/tidyText()").get(); //涨跌幅
                        String cjje = e.xpath("//td[6]/tidyText()").get(); //成交金额
                        String jmr = e.xpath("//td[7]/tidyText()").get(); //净买入


                        for (Selectable nodebuy : nodesBuy5) {
                            setValue(TotalBuy, YZBuyMX, YZBuy, nodebuy);
                        }
                        for (Selectable nodebuy : nodesSell5) {
                            setValue(TotalSell, YZSellMX, YZSell, nodebuy);
                        }

                        //位数 1：是 0否 第一个： 游资是否买 第二个 游资是否卖 第三个涨幅是否大于9.5% 第四个 是否为3日龙虎榜
                        StringBuffer state = new StringBuffer();
                        if (Strings.isNotBlank(YZBuyMX.toString())){
                            state.append("1");
                        }else {
                            state.append("0");
                        }

                        if (Strings.isNotBlank(YZSellMX.toString())){
                            state.append("1");
                        }else {
                            state.append("0");
                        }
                        int i1 = new BigDecimal(zdf.split("%")[0]).compareTo(new BigDecimal("9"));

                        if (i1 >=  1){
                            state.append("1");
                        }else {
                            state.append("0");
                        }

                        if (Strings.isNotBlank(labelType.trim())){
                            state.append("1");
                        }else {
                            state.append("0");
                        }
                        longHuBangDao.insert(LongHuBang.builder()
                                .reportTime(reportTime).code(code).name(name).price(price).zdf(zdf).cjje(cjje).jmr(jmr).reason(mx).transactionDetails(cjmx)
                                .buyYz(YZBuy.toString()).sellYz(YZSell.toString()).hotMoneyBuy(YZBuyMX.toString()).hotMoneySell(YZSellMX.toString()).buy(TotalBuy.toString()).sell(TotalSell.toString())
                                .labelType(labelType).state(state.toString())
                                .build());

                    });

                }
            }
            page.addTargetRequests(urlList);

        }
//        else {
//            //http://data.10jqka.com.cn/market/lhbgg/code/300337/
//            LambdaQueryWrapper<LongHuBang> wrapper = new LambdaQueryWrapper<>();
//            wrapper.like(LongHuBang::getTransactionDetails, page.getUrl());
//            wrapper.eq(LongHuBang::getReportTime, page.getUrl());
//            LongHuBang longHuBang = longHuBangDao.selectOne(wrapper);
//            String s = page.getHtml().xpath("//p[@class=\"mt4\"]//span/tidyText()").get();
//            longHuBang.setHy(s);
//        }

    }

    private void setValue(StringBuffer TotalBuy, StringBuffer YZBuyMX, StringBuffer YZBuy, Selectable nodebuy) {
        String yyb = nodebuy.xpath("//a[@class=\"details\"]/text()").get();//营业部
        String mre= nodebuy.xpath("//td[@class=\"c-rise tr rel\"]/text()").get(); //买入额
        String mce = nodebuy.xpath("//td[@class=\"c-fall tr rel\"]/text()").get();//卖出额
        yyb.replace("...","");
        //净额
        String je = new BigDecimal(mre).subtract(new BigDecimal(mce)).toString();
        //前5是买 后5是卖出
        TotalBuy.append(String.format(" '%s'买入'%s'万元 卖出 '%s'万元 净买入'%s'万元; ", yyb, mre, mce, je));
        LambdaQueryWrapper<HotMoneyInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(HotMoneyInfo::getSeat,yyb);
        HotMoneyInfo hotMoneyInfo = hotMoneyInfoDao.selectOne(wrapper);
        if (hotMoneyInfo != null){
            //游资席位
            YZBuyMX.append(String.format(" '%s'买入'%s'万元 卖出 '%s'万元 净买入'%s'万元; ", hotMoneyInfo.getName(), mre, mce, je));
            YZBuy.append(hotMoneyInfo.getName()).append("|");
        }
    }

    @Override
    public Site getSite() {
        return site;
    }
}








